<template>
    <el-upload ref="uploadRef" class="upload-demo" list-type="picture" :action="uploadFileUrl" :auto-upload="false"
        :before-upload="handleBeforeUpload" :on-error="handleUploadError" :on-exceed="handleExceed"
        :on-success="handleUploadSuccess" :on-remove="handleRemove" :headers="headers"
        accept="image/jpg,image/jpeg,image/png" :limit="1">
        <template #trigger>
            <el-button type="primary">{{ buttonString }}</el-button>
        </template>
        <template #tip>
            <div class="el-upload__tip">
                格式为png、jpeg或jpg
            </div>
        </template>
        <el-button class="ml-3" type="success" @click="submitUpload">
            上传到服务器
        </el-button>


    </el-upload>
</template>
<script lang="ts" setup>
import { getToken } from "@/utils/auth";
import { getCurrentInstance, ref } from "vue";
import { genFileId } from 'element-plus'
import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'
const props = defineProps({
    modelValue: [String, Object, Array],
    limit: {
        type: Number,
        default: 1,
    },
    fileType: {
        type: Array,
        default: ["jpg", "png", "jpeg"],
    },
    buttonString: {
        type: String,
        defalut: "请选择图片"
    }
});

const { proxy } = getCurrentInstance() as any;
const emit = defineEmits(["update:modelValue"]);
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadFileUrl = import.meta.env.VITE_APP_BASE_API + "/common/upload";
const headers = { Authorization: "Bearer " + getToken() };

const uploadRef = ref<UploadInstance>()

const submitUpload = () => {
    uploadRef.value!.submit()
}

const handleBeforeUpload = (file: any) => {
    proxy.$modal.loading("正在上传文件，请稍候...");
    return true;
}

// const upload = ref<UploadInstance>()


// 文件超过个数，就删除之前的那一个
const handleExceed: UploadProps['onExceed'] = (files) => {
    uploadRef.value!.clearFiles()
    const file = files[0] as UploadRawFile
    file.uid = genFileId()
    uploadRef.value!.handleStart(file)
}


const handleRemove = () => {
    uploadRef.value!.clearFiles();
}

// const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {

// }


// 上传失败
const handleUploadError = (err: any) => {
    proxy.$modal.msgError("上传图片失败");
};



// 上传成功回调
const handleUploadSuccess = (res: any, file: any) => {
    console.log("上传图片上传成功回调" + res);
    const url = res.data.url; // 假设上传成功后返回的 URL 存储在 response.data.url 中
    uploadRef.value!.clearFiles(); // 清空已上传的文件列表
    uploadRef.value!.$emit('upload-success', url); // 触发自定义事件并传递 URL
    emit("update:modelValue", url);
    proxy.$modal.closeLoading();
    proxy.$modal.msgSuccess("上传图片成功");

}

defineExpose({
    handleRemove
})
</script>



<style scoped>
/* 去除 upload 组件过渡效果，不然清除图片时会一闪而过 */
:deep(.el-upload-list__item) {
    transition: none !important;
}
</style>